﻿using AutoMapper;
using MediatR;
using SmartCity.ProcessEngine.Api.Write.Application.Command.FormDetail;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Interface;
using System.Transactions;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.Api.Write.Application.CommandHandler.FormDetail
{
    public class CreateFormFieldHandler : IRequestHandler<CreateFormFieldCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<FormFieldModel> formFieldRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateFormFieldHandler> logger;

        public CreateFormFieldHandler(IBaseRepository<FormFieldModel> formFieldRepo, IMapper mapper,ILogger<CreateFormFieldHandler> logger)
        {
            this.formFieldRepo = formFieldRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(CreateFormFieldCommand request, CancellationToken cancellationToken)
        {

            List<FormFieldModel> formFields = new List<FormFieldModel>();//实例化表单字段明细实体列表,,,,
            foreach (var dto in request.CreateFormFieldDTOs)//循环请求命令里的表单明细参数
            {
                FormFieldModel model = mapper.Map<FormFieldModel>(dto);   //把每一个dto转成model
                model.Id = YitIdHelper.NextId();
                formFields.Add(model);
            }

            var entities = formFieldRepo.GetAll().Where(x => x.FormId == request.FormId).ToList();
            foreach (var entity in entities) {
                entity.IsDeleted = true;  //批量修改逻辑删除标识为True
            }


            //事务:同时成功,同时失败
            var u = 0;
            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    u = await formFieldRepo.UpdateRangeAsync(entities);//批量逻辑删除现有的表单字段
                    r = await formFieldRepo.CreateRangeAsync(formFields);//批量添加新的表单字段
                    tran.Complete();//提交事务
                }
                catch (Exception e)
                {
                    logger.LogError($"发生异常,事务回滚:{e.Message}");
                    throw;
                }
                
            }
            if (r > 0)
            {
                return new ApiResult<int>().Success("保存流程表单明细成功!", r);
            }
            else
            {
                return new ApiResult<int>().Fail("保存流程表单明细失败!");
            }

        }
    }
}
